﻿using System.Collections.ObjectModel;

namespace WpfApplication5.ViewModels
{
    public class TreeViewItemViewModel:ViewModelBase
    {
        static readonly TreeViewItemViewModel DummyChild = new TreeViewItemViewModel();
        readonly ObservableCollection<TreeViewItemViewModel> _children;
        readonly TreeViewItemViewModel _parent;
        bool _isExpanded;
        bool _isSelected;

        private TreeViewItemViewModel()
        {

        }
        public TreeViewItemViewModel(TreeViewItemViewModel parent, bool lazyLoadChildren = false)
        {
            _parent = parent;
            _children = new ObservableCollection<TreeViewItemViewModel>();
            if (lazyLoadChildren)
            {
                _children.Add(DummyChild);
            }
        }

        public ObservableCollection<TreeViewItemViewModel> Children
        {
            get { return _children; }
        }

        public TreeViewItemViewModel Parent
        {
            get { return _parent; }
        }
        public bool HasDummyChild
        {
            get { return this.Children.Count == 1 && this.Children[0] == DummyChild; }
        }

        public bool IsExpanded
        {
            get { return _isExpanded; }
            set
            {
                if (value != _isExpanded)
                {
                    _isExpanded = value;
                    OnPropertyChanged(() => this.IsExpanded);
                }
                if (_isExpanded && _parent != null)
                    _parent.IsExpanded = true;

                if (this.HasDummyChild)
                {
                    this.Children.Remove(DummyChild);
                    this.LoadChildren();
                }
            }
        }

        public bool IsSelected
        {
            get { return _isSelected; }
            set
            {
                if (value != _isSelected)
                {
                    _isSelected = value;
                    OnPropertyChanged(() => this.IsSelected);
                }
            }
        }

        protected virtual void LoadChildren()
        {
        }
    }
}
